package com.example.bootintegration.datasource;

import com.zaxxer.hikari.HikariDataSource;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.datasource.DelegatingDataSource;

import javax.sql.DataSource;


/**
 * @author Quintoy
 * @date 12/30/22
 */
public class ConfigurableDataSource extends DelegatingDataSource {
    private String name;
    private Environment env;
    private DataSource delegate;

    public ConfigurableDataSource(String name, Environment env) {
        this.name = name;
        this.env = env;
        this.delegate = this.createDelegate();
        super.setTargetDataSource(delegate);
    }

    private String getPrefix() {
        return "boot.datasource." + this.name;
    }

    private HikariDataSource createDelegate() {

        HikariDataSource dataSource = new HikariDataSource();
        dataSource.setPoolName(this.name);
        dataSource.setJdbcUrl(getProperty("url"));
        dataSource.setDriverClassName(getProperty("driverClassName"));
        dataSource.setUsername(getProperty("username"));
        dataSource.setPassword(getProperty("password"));
        return dataSource;
    }


    private String getProperty(String property) {
        return env.getProperty(getPrefix() + "." + property);
    }
}
